package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.DmcSleepCareBindMapper;
import com.csun.cmny.provider.exceptions.DmcBizException;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.domain.DmcSleepCareBind;
import com.csun.cmny.provider.model.dto.propertyManagement.SelectDeviceDataDto;
import com.csun.cmny.provider.model.dto.sleep.BedOldmanSleepReqDto;
import com.csun.cmny.provider.model.dto.sleepcare.BindSleepCareDto;
import com.csun.cmny.provider.model.dto.sleepcare.SleepCarePageQuery;
import com.csun.cmny.provider.model.enums.button.DmcCsunButtonBindTypeEnum;
import com.csun.cmny.provider.model.enums.csunsleep.DmcCsunSleepBindTypeEnum;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.enums.sleepcare.DmcSleepCareBindTypeEnum;
import com.csun.cmny.provider.model.vo.DmcSleepCareVo;
import com.csun.cmny.provider.model.vo.OldmanBedRoomBuildingVo;
import com.csun.cmny.provider.model.vo.SleepCareDataReqVo;
import com.csun.cmny.provider.model.vo.propertyManagement.PropertyDataVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.csun.cmny.provider.service.DmcSleepCareBindService;
import com.csun.cmny.provider.service.OmcRpcService;
import com.csun.cmny.util.PubUtils;
import com.csun.cmny.util.PublicUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-02-13 15:51
 * @Description: the class dmc sleep care bind service impl
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DmcSleepCareBindServiceImpl extends BaseService<DmcSleepCareBind>
        implements DmcSleepCareBindService {

    @Resource
    private DmcDeviceService dmcDeviceService;

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private DmcSleepCareBindMapper dmcSleepCareBindMapper;

    @Resource
    private OmcRpcService omcRpcService;

    /**
     * query group sleep care list with page
     *
     * @param sleepCarePageQuery    sleep care page query
     *
     * @return  the page info.
     */
    @Override
    public PageInfo queryGroupSleepCareListWithPage(SleepCarePageQuery sleepCarePageQuery) {

        PageHelper.startPage(sleepCarePageQuery.getPageNum(), sleepCarePageQuery.getPageSize());

        List<DmcSleepCareVo> dmcSleepCareVoList = dmcSleepCareBindMapper
                .queryGroupSleepCareListWithPage(sleepCarePageQuery);

        return new PageInfo<>(dmcSleepCareVoList);
    }

    /**
     * bind sleep care
     *
     * @param bindSleepCareDto  bind sleep care dto
     * @param loginAuthDto      login auth dto
     *
     * @return  the int.
     */
    @Override
    public Integer bindSleepCare(BindSleepCareDto bindSleepCareDto, LoginAuthDto loginAuthDto) {

        // 1.校验睡眠卫士
        DmcDevice dmcDevice = dmcDeviceService.checkDeviceIsSleepCareByDeviceId(bindSleepCareDto.getDeviceId());
        if (PublicUtil.isEmpty(dmcDevice)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610037, bindSleepCareDto.getDeviceId());
        }

        // 2.校验睡眠卫士是否已经被绑定
        DmcSleepCareBind dmcSleepCareBindQuery = dmcSleepCareBindMapper
                .selectByPrimaryKey(bindSleepCareDto.getDeviceId());
        if (PublicUtil.isNotEmpty(dmcSleepCareBindQuery)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610038, dmcSleepCareBindQuery.getDeviceId(),
                    dmcSleepCareBindQuery.getLocation());
        }

        // 3.校验绑定类型
        Preconditions.checkArgument(!PubUtils.isNull(bindSleepCareDto.getBindType()),
                cmnyMessageSource.getMessage("sleep.care.bind.type.null", null));

        Preconditions.checkArgument(bindSleepCareDto.getBindType() >= 0
                        && bindSleepCareDto.getBindType() <= 2,
                cmnyMessageSource.getMessage("sleep.care.bind.type.range", null));

        // 4.校验位置
        if (bindSleepCareDto.getBindType().equals(DmcSleepCareBindTypeEnum.CUSTOM.getKey())) {
            Preconditions.checkArgument(!PubUtils.isNull(bindSleepCareDto.getLocation()),
                    cmnyMessageSource.getMessage("sleep.care.bind.location.null", null));
        }

        // 4.校验老人
        if (bindSleepCareDto.getBindType().equals(DmcSleepCareBindTypeEnum.OLDMAN.getKey())) {
            // 校验老人Id和老人姓名
            Preconditions.checkArgument(!PubUtils.isNull(bindSleepCareDto.getOldmanId()),
                    cmnyMessageSource.getMessage("sleep.care.bind.oldman.id.null", null));

            Preconditions.checkArgument(!PubUtils.isNull(bindSleepCareDto.getOldmanName()),
                    cmnyMessageSource.getMessage("sleep.care.bind.oldman.name.null", null));
            // TODO 校验老人Id是否存在
            OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo = omcRpcService
                    .queryOldmanBedRoomBuildingByOldmanId(bindSleepCareDto.getOldmanId());
            if (PublicUtil.isEmpty(oldmanBedRoomBuildingVo)) {
                // 老人不存在
                throw new DmcBizException(ErrorCodeEnum.DMC100610062);
            }

            /**
             * @date    2019-05-22
             * @author  chisj
             * @desc    校验老人是否绑定过智能床垫
             */
            dmcSleepCareBindQuery = new DmcSleepCareBind();
            dmcSleepCareBindQuery.setBindType(DmcCsunSleepBindTypeEnum.OLDMAN.getKey());
            dmcSleepCareBindQuery.setOldmanId(bindSleepCareDto.getOldmanId());
            int count = dmcSleepCareBindMapper.selectCount(dmcSleepCareBindQuery);
            if (count > 0) {
                // 老人已经绑定了智能床垫
                throw new DmcBizException(ErrorCodeEnum.DMC100610068);
            }

            bindSleepCareDto.setOldmanName(oldmanBedRoomBuildingVo.getOldmanName());
            if (PublicUtil.isNotEmpty(oldmanBedRoomBuildingVo.getBedId())) {
                bindSleepCareDto.setBedId(oldmanBedRoomBuildingVo.getBedId());
                bindSleepCareDto.setLocation(oldmanBedRoomBuildingVo.getLocation());
            }
        }

        // 5.校验床位Id
        if (bindSleepCareDto.getBindType().equals(DmcCsunButtonBindTypeEnum.BED.getKey())) {
            // 绑定类型为房间
            Preconditions.checkArgument(!PubUtils.isNull(bindSleepCareDto.getBedId()),
                    cmnyMessageSource.getMessage("sleep.care.bind.bed.id.null", null));
            // 校验床位Id是否存在
            // TODO 校验床位Id是否存在
            OldmanBedRoomBuildingVo bedRoomBuildingVo = omcRpcService
                    .queryOldmanBedRoomBuildingByBedId(bindSleepCareDto.getBedId());
            if (PublicUtil.isEmpty(bedRoomBuildingVo)) {
                // 床位不存在
                throw new DmcBizException(ErrorCodeEnum.DMC100610060);
            }

            /**
             * @date    2019-05-22
             * @author  chisj
             * @desc    校验床位是否绑定过智能床垫
             */
            dmcSleepCareBindQuery = new DmcSleepCareBind();
            dmcSleepCareBindQuery.setBindType(DmcCsunSleepBindTypeEnum.BED.getKey());
            dmcSleepCareBindQuery.setBedId(bindSleepCareDto.getBedId());
            int count = dmcSleepCareBindMapper.selectCount(dmcSleepCareBindQuery);
            if (count > 0) {
                // 老人已经绑定了智能床垫
                throw new DmcBizException(ErrorCodeEnum.DMC100610069);
            }

            bindSleepCareDto.setOldmanId(bedRoomBuildingVo.getOldmanId());
            bindSleepCareDto.setOldmanName(bedRoomBuildingVo.getOldmanName());
            bindSleepCareDto.setLocation(bedRoomBuildingVo.getLocation());
        }

        // 6.添加绑定
        DmcSleepCareBind dmcSleepCareBind = new DmcSleepCareBind();
        BeanUtils.copyProperties(bindSleepCareDto, dmcSleepCareBind);
        dmcSleepCareBind.setUpdateInfo(loginAuthDto);

        return dmcSleepCareBindMapper.insertSelective(dmcSleepCareBind);

    }

    /**
     * break sleep care
     *
     * @param deviceId  device id
     *
     * @return  the int.
     */
    @Override
    public Integer breakSleepCare(Long deviceId) {

        // 1.判断设备Id是否存在
        DmcDevice dmcDevice = dmcDeviceService.checkDeviceIsSleepCareByDeviceId(deviceId);
        if (PublicUtil.isEmpty(dmcDevice)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610037, deviceId);
        }

        // 2.判断紧急按钮是否已经绑定
        DmcSleepCareBind dmcSleepCareBindQuery = dmcSleepCareBindMapper
                .selectByPrimaryKey(deviceId);
        if (PublicUtil.isEmpty(dmcSleepCareBindQuery)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610039, deviceId);
        }

        // 3.解绑紧急按钮
        return dmcSleepCareBindMapper.deleteByPrimaryKey(deviceId);

    }

    /**
     * query sleep care bind list all
     *
     * @return the list
     */
    @Override
    public List<DmcSleepCareVo> querySleepCareBindListAll() {

        SleepCarePageQuery sleepCarePageQuery = new SleepCarePageQuery();
        sleepCarePageQuery.setDeviceType(DmcDeviceTypeEnum.BS_SLEEP.getIndex());

        return dmcSleepCareBindMapper.queryGroupSleepCareListWithPage(sleepCarePageQuery);
    }

    /**
     * get sleep care bind by device id
     *
     * @param deviceId device id
     * @return dmc sleep care vo
     */
    @Override
    public DmcSleepCareVo getSleepCareBindByDeviceId(Long deviceId) {

        SleepCarePageQuery sleepCarePageQuery = new SleepCarePageQuery();
        sleepCarePageQuery.setDeviceType(DmcDeviceTypeEnum.BS_SLEEP.getIndex());
        sleepCarePageQuery.setDeviceId(deviceId);

        PageHelper.startPage(1, 1);
        List<DmcSleepCareVo> dmcSleepCareVos = dmcSleepCareBindMapper
                .queryGroupSleepCareListWithPage(sleepCarePageQuery);

        if (PubUtils.isNull(dmcSleepCareVos)) {
            return null;
        }

        return dmcSleepCareVos.get(0);
    }

    /**
     * get sleep care bind by device no
     *
     * @param deviceNo device no
     * @return dmc csun sleep vo
     */
    @Override
    public DmcSleepCareVo getSleepCareBindByDeviceNo(String deviceNo) {

        SleepCarePageQuery sleepCarePageQuery = new SleepCarePageQuery();
        sleepCarePageQuery.setDeviceType(DmcDeviceTypeEnum.BS_SLEEP.getIndex());
        sleepCarePageQuery.setDeviceNo(deviceNo);

        PageHelper.startPage(1, 1);
        List<DmcSleepCareVo> dmcSleepCareVos = dmcSleepCareBindMapper
                .queryGroupSleepCareListWithPage(sleepCarePageQuery);

        if (PubUtils.isNull(dmcSleepCareVos)) {
            return null;
        }

        return dmcSleepCareVos.get(0);
    }

    /**
     * get sleep care bind by oldman id
     *
     * @param oldmanId oldman id
     * @return dmc csun sleep vo
     */
    @Override
    public DmcSleepCareVo getSleepCareBindByOldmanId(Integer oldmanId) {

        SleepCarePageQuery sleepCarePageQuery = new SleepCarePageQuery();
        sleepCarePageQuery.setDeviceType(DmcDeviceTypeEnum.BS_SLEEP.getIndex());
        sleepCarePageQuery.setOldmanId(oldmanId);

        PageHelper.startPage(1, 1);
        List<DmcSleepCareVo> dmcSleepCareVos = dmcSleepCareBindMapper
                .queryGroupSleepCareListWithPage(sleepCarePageQuery);

        if (PubUtils.isNull(dmcSleepCareVos)) {
            return null;
        }

        return dmcSleepCareVos.get(0);
    }

    /**
     * query sleep care data by bed oldman list
     *
     * @param bedOldmanSleepReqDtoList bed oldman sleep req dto list
     *
     * @return  the list.
     */
    @Override
    public List<SleepCareDataReqVo> querySleepCareDataByBedOldmanList(List<BedOldmanSleepReqDto> bedOldmanSleepReqDtoList) {

        return dmcSleepCareBindMapper.querySleepCareDataByBedOldmanList(bedOldmanSleepReqDtoList);
    }

    @Override
    public List<PropertyDataVo> selectDeviceData(SelectDeviceDataDto selectDeviceDataDto) {
        return dmcSleepCareBindMapper.selectDeviceData(selectDeviceDataDto);
    }
}
